package com.heyu.cgsd.model.http;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OKHttp implements Callback {

    private static final String API_KEY = "622c8f754e8227b8704326837eb0cfb1";

    private Handler handler = new Handler(Looper.getMainLooper());
    private static IDataListener dataListener;

    public static void getCurrency(String from, String to, IDataListener call) {
        dataListener = call;
        String url = "http://op.juhe.cn/onebox/exchange/currency?key=" + API_KEY + "&from=" + from + "&to=" + to;
        Request request = new Request.Builder().url(url).build();
        //异步请求
        new OkHttpClient().newCall(request).enqueue(new OKHttp());
    }

    @Override
    public void onFailure(Call call, IOException e) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (dataListener != null) {
                    dataListener.onFailure();
                }
            }
        });
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        final String content = response.body().string();
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(content)) {
                    dataListener.onFailure();
                } else if (dataListener != null) {
                    dataListener.onSuccess(content);
                }
            }
        });
    }

    public interface IDataListener {
        void onSuccess(String data);
        void onFailure();
    }

}
